jQuery(document).ready(function(){
	jQuery(".leftmenu ul li").removeClass("current");
	jQuery(".leftmenu ul li a.routes").parent().addClass("current");
	
	//dual box
	var db = jQuery('#dualselect').find('.ds_arrow .arrow');	//get arrows of dual select
	var sel1 = jQuery('#dualselect select:first-child');		//get first select element
	var sel2 = jQuery('#dualselect select:last-child');			//get second select element
	
	sel2.empty(); //empty it first from dom.
	
	db.click(function(){
		var t = (jQuery(this).hasClass('ds_prev'))? 0 : 1;	// 0 if arrow prev otherwise arrow next
		if(t) {
			sel1.find('option').each(function(){
				if(jQuery(this).is(':selected')) {
					jQuery(this).attr('selected',false);
					var op = sel2.find('option:first-child');
					sel2.append(jQuery(this));
				}
			});	
		} else {
			sel2.find('option').each(function(){
				if(jQuery(this).is(':selected')) {
					jQuery(this).attr('selected',false);
					sel1.append(jQuery(this));
				}
			});		
		}
	});

	var submit = jQuery('#submit-button');
	var geoName = jQuery('#geoName');
	var geoId = jQuery('#geoId');
	submit.click(function(){
		var name = '';
		var id = '';
		var i = 1;
		sel2.find('option').each(function(){
			name+=jQuery(this).text().trim();
			id+=jQuery(this).val();
			if(i<sel2.find('option').size())
			{
				name += ',';
				id += ',';
			}
			i++;
		});	
		geoName.val(name);
		geoId.val(id);
	});
	
	//Get district
	jQuery("select[name=city]").bind("change", changeCity);
	function changeCity() {
		var id = jQuery(this).val();
		loadDistrict(id, "");
	}
	
	//Get ward
	jQuery("select[name=district]").bind("change", changeDistrict);
	function changeDistrict() {
		var id = jQuery(this).val();
		loadWard(id, "");
	}
});

function loadCity(selected) {
	jQuery.ajax({
		type: "POST",
		url: "/ajax-get-city",
		data: {},
		dataType: "html",
		success: function(response)
		{
			jQuery("select[name=city]").html(response);
			jQuery("select[name=city]").val(selected);
		}
	});
}

function loadDistrict(id, selected) {
	jQuery.ajax({
		type: "POST",
		url: "/ajax-get-district",
		data: {id: id},
		dataType: "html",
		success: function(response)
		{
			jQuery("select[name=district]").html(response);
			jQuery("select[name=district]").val(selected);
		}
	});
}

function loadWard(id, selected) {
	jQuery.ajax({
		type: "POST",
		url: "/ajax-get-ward",
		data: {id: id,action: "route"},
		dataType: "html",
		success: function(response)
		{
			jQuery("select[name=ward]").html(response);
			jQuery("select[name=ward]").val(selected);
		}
	});
}